package com.enterprise.support.utility;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.*;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

import java.io.*;

public class LuceneUtility {
    private IndexWriter indexWriter = null;
    private StandardAnalyzer analyzer = null;
    private IndexSearcher searcher = null;
    private static LuceneUtility luceneUtility = new LuceneUtility();
    private IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_31, analyzer);

    private LuceneUtility() {
        try {
            analyzer = new StandardAnalyzer(Version.LUCENE_34);
            //indexWriter = new IndexWriter(FSDirectory.open(new File("c://index")), indexWriterConfig);
            indexWriter = new IndexWriter(FSDirectory.open(new File("c://index")), analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void update(Document document) {
        try {
            indexWriter.updateDocument(new Term("path", "/"), document);
            indexWriter.commit();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void add(Document document) {
        try {
            indexWriter.addDocument(document);
            indexWriter.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static LuceneUtility getInstance() {
        return luceneUtility;
    }

    public static void main(String[] args) {
        LuceneUtility luceneUtility = LuceneUtility.getInstance();

        Document document = new Document();
        Field pathField = new Field("path", "c://text.text", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
        pathField.setIndexOptions(FieldInfo.IndexOptions.DOCS_ONLY);

        Field content = new Field("content", "=============", Field.Store.YES, Field.Index.ANALYZED);
        document.add(pathField);
        document.add(content);
        luceneUtility.add(document);
    }
}